!function () {
    const $ = mdui.$;
    const admin = {};
    const pushStateBackup = history.pushState;

    admin.page = -1;
    admin.isCanChangeUrl = true;
    admin.nowLoadBorder = null;
    admin.pagesData = null;
    admin.pageSwitchTab = null;

    function getCorrectURL(path) {
        return (location.pathname.slice(-1) == "/" ? "./" : "./admin/") + path;
    }

    function createLoadBorder() {
        if (admin.nowLoadBorder) {
            admin.nowLoadBorder.off();
            admin.nowLoadBorder = null;
        }
        const core = $("<div class='ds-loadborder'></div>")
        core.appendTo(document.body)
        core.css("opacity", "1");
        let rate = 0;
        setTimeout(() => {
            rate = 10;
        }, 300)
        const loopId = setInterval(() => {
            core.css("width", rate + "%");
            rate += 0.5;
            if (rate > 98) {
                clearInterval(w);
            }
        }, 250)
        return {
            off() {
                clearInterval(loopId);
                core.addClass('ds-loadborder-done')
                core.css("width", "100%")
                core.css("opacity", "0")
                setTimeout(() => {
                    core[0].remove()
                }, 300)
            }
        }
    }

    function pageItemClick() {
        if ($(this).hasClass("mdui-list-item-active")) return;
        history.pushState({}, "", "#" + this.path);
        $("iframe").attr("src", getCorrectURL("page?a=" + encodeURIComponent(this.path)));
        admin.nowLoadBorder = createLoadBorder();
        $(".mdui-list-item").each((_, item) => {
            $(item).removeClass("mdui-list-item-active")
        })
        $(this).addClass("mdui-list-item-active")
    }

    function updateList() {
        if (admin.page !== admin.pageSwitchTab.activeIndex) {
            admin.page = admin.pageSwitchTab.activeIndex;

            $(`.mdui-drawer .mdui-list`).html("");

            if (admin.pageSwitchTab.activeIndex == 0) {
                admin.nowLoadBorder = createLoadBorder();
                $(document.body).addClass("ds-home");
                $('.ds-drawer').prop('disabled', true)
                $("iframe").attr("src", getCorrectURL("page?a=home"));
                history.pushState({}, "", "#");
            } else {
                var category = admin.pagesData.find((_, index) => index == admin.pageSwitchTab.activeIndex - 1);
                var groups = category[2];

                $(document.body).removeClass("ds-home");
                $('.ds-drawer').prop('disabled', false)

                groups.forEach((group, groupIndex) => {
                    if (typeof group[2] == "string") {
                        var item = $(`<a class="mdui-list-item mdui-ripple"><i class="mdui-list-item-icon mdui-icon material-icons"></i><div class="mdui-list-item-content"></div></a>`);
                        item.find(".mdui-icon").text(group[2]);
                        item.find(".mdui-list-item-content").text(group[0]);
                        item.prop("path", `${category[1]}/${group[1]}`);
                        item.on("click", pageItemClick);
                        $(`.mdui-drawer .mdui-list`).append(item);
                    } else {
                        var pages = group[2];
                        var item = $(`<li class="mdui-subheader"></li>`);
                        item.text(group[0]);
                        $(`.mdui-drawer .mdui-list`).append(item);
                        pages.forEach(page => {
                            var item = $(`<a class="mdui-list-item mdui-ripple"><i class="mdui-list-item-icon mdui-icon material-icons"></i><div class="mdui-list-item-content"></div></a>`);
                            item.find(".mdui-icon").text(page[2]);
                            item.find(".mdui-list-item-content").text(page[0]);
                            item.prop("path", `${category[1]}/${group[1]}/${page[1]}`);
                            item.on("click", pageItemClick);
                            $(`.mdui-drawer .mdui-list`).append(item);
                        })
                    }
                    if (groupIndex == groups.length - 1) {
                        if (admin.isCanChangeUrl) $(`.mdui-list-item`)[0].click()
                    }
                })
            }
        }
    }

    function updateByURL() {
        admin.isCanChangeUrl = false;
        var hash = location.hash.slice(1);
        if (hash === "") {
            $(".mdui-appbar > .mdui-tab > a:nth-child(1)")[0].click();
        } else {
            var path = hash.split("/");
            var index = admin.pagesData.map((v, i) => [v, i]).find(v => v[0][1] == path[0])[1];
            $(".mdui-appbar > .mdui-tab > *")[index + 1].click();
            $(`.mdui-list-item`).filter((_, v) => v.path == hash)[0].click();
        }
        admin.isCanChangeUrl = true;
    }

    function iframOnLoad() {
        if (admin.nowLoadBorder) {
            admin.nowLoadBorder.off();
            admin.nowLoadBorder = null;
        }
    }

    function onPopstate() {
        updateByURL()
    }

    function newPushState(d, n, u) {
        if (admin.isCanChangeUrl) {
            pushStateBackup.apply(this, [d, n, u]);
        }
    }

    function sizeChangeLoopCallback() {
        $(".ds-main").css("height", $(window).height() - $(".mdui-appbar").height());
    }

    window.addEventListener('popstate', onPopstate);

    history.pushState = newPushState;

    setInterval(sizeChangeLoopCallback, 100);

    $("iframe").on("load", iframOnLoad);

    $.ajax({
        url: getCorrectURL('api/get_pages'),
        method: 'GET',
        success: function (response) {
            const list = JSON.parse(response).data;
            admin.pagesData = list;
            list.forEach(e => {
                var a = $(`<a class="mdui-ripple"></a>`);
                a.text(e[0]);
                $(`.mdui-appbar .mdui-tab`).append(a);
            });

            const pageSwitchTab = new mdui.Tab($(`.mdui-appbar .mdui-tab`));
            admin.pageSwitchTab = pageSwitchTab;
            $(`.mdui-appbar .mdui-tab>a`).each((i, v) => {
                $(v).on("click", function () {
                    updateList();
                })
            });

            updateByURL();
        },
        error: function (xhr, status, error) {
            console.log(error);
        }
    })

    window.admin_ = admin;
}()